using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using static DBService.Utils.UnityDebugUtils;

#nullable enable
namespace OA
{
    [Serializable]
    public class ExternalContentInfo
    {
        /// <summary>
        /// 包名称，必需
        /// </summary>
        public string name = string.Empty;
        /// <summary>
        /// 版本号，必需
        /// </summary>
        public string version = string.Empty;

        public const string defaultCompanyName = "DefaultCompany";
        /// <summary>
        /// 公司名，自动填写
        /// </summary>
        public string companyName = defaultCompanyName;
        /// <summary>
        /// 产品名，自动填写
        /// </summary>
        public string productName = string.Empty;

        /// <summary>
        /// 创建日期，可空
        /// </summary>
        public DateTime? date;
        /// <summary>
        /// 简述，可空
        /// </summary>
        public string? description;
        /// <summary>
        /// 目录文件，可空。
        /// 来自 json 时填写相对路径，加载过程中会替换为绝对路径
        /// </summary>
        public string? catalog;


        public static ExternalContentInfo? ConvertFrom(string jsonStr)
        {
            JToken? token = null;
            // https://stackoverflow.com/questions/14977848/how-to-make-sure-that-string-is-valid-json-using-json-net
            try
            {
                token = JToken.Parse(jsonStr);
            }
            catch (JsonReaderException jex)
            {
                PrintErr("bad parse json", jex);

            }
            catch (Exception ex) //some other exception
            {
                PrintErr("other exception with json parsing", ex);
            }
            if (token == null || !token.HasValues) { return null; }

            var _name = token.Value<string>(nameof(name));
            var _version = token.Value<string>(nameof(version));
            if (string.IsNullOrEmpty(_name) || string.IsNullOrEmpty(_version))
            {
                return null;
            }

            return new ExternalContentInfo
            {
                name = _name,
                version = _version,
                companyName = token.Value<string>(nameof(companyName)),
                productName = token.Value<string>(nameof(productName)),
#pragma warning disable IDE0004  // Unity 的 .Net 版本不支持隐式转换可空值类型
                date = DateTime.TryParse(token.Value<string>(nameof(date)), out var d) ? d : (DateTime?)null,
#pragma warning restore  // Unity 的 .Net 版本不支持隐式转换可空值类型
                description = token.Value<string>(nameof(description)),
                catalog = token.Value<string>(nameof(catalog))
            };
        }
    }
}